package com.avic.rong.fragment.collect;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.rong.R;
import com.avic.rong.activity.mine.CollectionActivity;
import com.avic.rong.adapter.collect.ArticleAdapter;
import com.avic.rong.api.collect.ArticleCollectApi;
import com.avic.rong.bean.collect.ArticleCollectBean;
import com.avic.rong.fragment.BaseLazyFragment;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class ArticleFragment extends BaseLazyFragment implements OnRefreshLoadMoreListener{


    @BindView(R.id.recv_article)
    RecyclerView recv_article;
    @BindView(R.id.srl_article)
    SmartRefreshLayout srl_article;
    @BindView(R.id.tv_wushujv)
    TextView tvWuShujv;

    private View view;
    private Unbinder unbinder;
    private int limit = 10;
    private int offset = 1;

    private ArrayList<ArticleCollectBean> mList;
    private String logintoken;
    private ArticleAdapter articleAdapter;

    //测式用的 token w4/b+EQcZZnFlmpDOn6EJH49BIWDoQfvty5QOPgq/+YLF2xTVRyFnfxTic0l1spU1DKp8PMVM1YSixxW8qPiUHQ9CAb6QSHI

   // public static String token = "w4/b+EQcZZnFlmpDOn6EJH49BIWDoQfvty5QOPgq/+YLF2xTVRyFnfxTic0l1spU1DKp8PMVM1YSixxW8qPiUHQ9CAb6QSHI";

    private int mPosition;
    private int newOffset;
    private ArticleCollectApi articleCollectApi;
    private boolean isRefresh;
    private LoadingLayout loading_layout;

    public ArticleFragment() {
        // Required empty public constructor
    }

    private String title;
    private Context mContext;


    private int pos;

    public static ArticleFragment getInstance(String title, Context mContext) {
        ArticleFragment articleFragment = new ArticleFragment();
        articleFragment.title = title;
        articleFragment.mContext = mContext;
        return articleFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (SharedPreferencesUtil.isLogin()) {
            logintoken = SharedPreferencesUtil.getLoginToken();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_article, container, false);
        unbinder = ButterKnife.bind(this, inflate);
        loading_layout = inflate.findViewById(R.id.loading_layout);
        loading_layout.setStatus(LoadingLayout.LOADING);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recv_article.setLayoutManager(linearLayoutManager);

        mList = new ArrayList<>();
        articleAdapter = new ArticleAdapter(getContext(),logintoken, mList);

        recv_article.setAdapter(articleAdapter);

        loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                HttpManager.getInstance().doHttpDeal(articleCollectApi);
                loading_layout.setStatus(LoadingLayout.LOADING);
            }

            @Override
            public void onReturn(View v) {
                getActivity().onBackPressed();
            }
        });

        srl_article.setOnRefreshLoadMoreListener(this);

        return inflate;
    }


    private void initData() {
        articleCollectApi = new ArticleCollectApi((CollectionActivity) getActivity(), new MyHttpListener());
        articleCollectApi.setArgument(logintoken, offset, limit);
        articleCollectApi.setCache(false);
//        articleCollectApi.setCancel(false);
//        articleCollectApi.setShowProgress(true);
        HttpManager.getInstance().doHttpDeal(articleCollectApi);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        isRefresh = false;
        offset = offset + 1;
        articleCollectApi.setOffset(offset);
        HttpManager.getInstance().doHttpDeal(articleCollectApi);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        isRefresh = true;
        offset = 1;
        articleCollectApi.setOffset(offset);
        HttpManager.getInstance().doHttpDeal(articleCollectApi);
    }

    @Override
    public void loadData() {
        initData();
    }

    public class MyHttpListener extends HttpOnNextListener<BaseResultEntity> {


        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                List<ArticleCollectBean> data = (List<ArticleCollectBean>) baseResultEntity.getData();
                Log.e("ArticleFragment", "onNext: " + data.toString());
                loading_layout.setStatus(LoadingLayout.SUCCESS);
                if (data != null) {

                    if (isRefresh){
                        mList.clear();
                    }

                    mList.addAll(data);
                    articleAdapter.notifyDataSetChanged();

                    if (mList!=null&&mList.size()<=0){
                        loading_layout.setStatus(LoadingLayout.EMPTY);
                        loading_layout.setEmptyImageVisible(true);
                        loading_layout.setEmptyText("您还未添加过收藏哦~");
                        loading_layout.setEmptyImage(R.mipmap.collection_mpty);
                    }

                   // articleAdapter.notifyItemRangeChanged(mList.size(),data.size());
                }
                if (srl_article!=null) {
                    if (isRefresh) {
                        srl_article.finishRefresh();
                    } else {
                        srl_article.finishLoadMore();
                    }
                }
            }else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
